<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class Synchronize extends Command {
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'synchronize:num';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'synchronize of comment_nums and approve_nums';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct() {
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle() {
		$this->info('---begin---');
		DB::table('items')->orderBy('id')->chunk(50, function ($items) {
			if (empty($items)) {
				return false;
			}
			foreach ($items as $item) {
				$this->handleOne($item);
			}
		});

	}

	private function handleOne($item) {
		$this->info('---' . $item->id . '---');
		$save_array = [
			'approve_nums' => DB::table('approves')->where('item_id', $item->id)->count(),
			'comment_nums' => DB::table('comments')->where('item_id', $item->id)->count(),
		];
		DB::table('items')->where('id', $item->id)->update($save_array);
		$this->info('---success---');
	}
}
